import { defineStore } from 'pinia'
import { login, getInfo, logout } from '@/api/login'
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
import { constantRoute } from '@/router/routers'

const useUserStore = defineStore('User', {
  //小仓库存储数据地方
  state: () => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      buttons: [],
    }
  },
  actions: {
    //用户登录的方法
    async userLogin(data) {
      //登录请求
      const result = await login(data)
      if (result.code == 200) {
        this.token = result.data
        //本地存储持久化存储一份
        SET_TOKEN(this.token)
        //能保证当前async函数返回一个成功的promise
        return 'ok'
      } else {
        return Promise.reject(new Error(result.msg))
      }
    },
    async userInfo() {
      const result = await getInfo()
      if (result.code == 200) {
        this.username = result.data.username
        this.avatar = result.data.avatar
        return 'ok'
      } else {
        return Promise.reject(new Error(result.msg))
      }
    },
    //退出登录
    async userLogout() {
      const result = await logout()

      if (result.code == 200) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.msg))
      }
    },
  },
  getters: {},
})
export default useUserStore
